<template>
  <div class="ticketListBox">
    <!-- 任务列表 -->
    <div class="list" v-if="boxStatus == 1">
      <div class="title">
        <div class="searchInfo" ref="searchInfo">
          <span class="searchBtn" @click="searchNameShow">
            <i class="el-icon-search"></i>
          </span>

          <!-- <el-input
            v-show="false"
            @keyup.enter.native="searchNameList($event)"
            ref="inputRef"
            v-model="listParams.line_name"
            type="text"
            @clear="queryKeyNull"
            clearable
            placeholder="请输入搜索内容"
          ></el-input> -->

          <el-autocomplete
            v-if="isShowSearchName"
            @keyup.enter.native="searchNameList($event)"
            ref="inputRef"
            v-model="listParams.line_name"
            type="text"
            @clear="queryKeyNull"
            clearable
            placeholder="请输入搜索内容"
            :fetch-suggestions="historySearch"
            @select="handleSelectHistory"
          >
            <template slot-scope="{ item }" popper-class="input-with-select">
              <div class="historyItem">
                <svg-icon class="history-icon" icon-class="history" />
                <div class="history-text">{{ item }}</div>
              </div>
            </template>
          </el-autocomplete>
        </div>
        <div class="title_left">
          <el-date-picker
            v-model="dateValue2"
            type="daterange"
            class="mydatepicker"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            align="right"
            unlink-panels
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            size="mini"
            :picker-options="pickerOptions"
            @change="changeData"
            @focus="showMask = true"
            @blur="showMask = false"
          />
        </div>
      </div>
      <div class="block body">
        <!-- 标题 -->
        <div class="body_title">
          <div class="body_title_text">任务列表</div>

          <div class="body_title_select">
            <el-select
              class="workTypeSelect"
              v-model="listParams.aim"
              placeholder="类型筛选"
              @change="ticketOptionChange"
              clearable
              size="mini"
            >
              <el-option
                v-for="item in ticketAimOptions"
                :key="item.key"
                :label="item.value"
                :value="item.key"
              >
              </el-option>
            </el-select>
            <el-select
              class="workStateSelect"
              v-model="listParams.state"
              placeholder="状态筛选"
              @change="ticketOptionChange"
              clearable
              size="mini"
            >
              <el-option
                v-for="item in ticketStateOptions"
                :key="item.key"
                :label="item.value"
                :value="item.key"
              >
              </el-option>
            </el-select>
          </div>
        </div>
        <div class="body_list">
          <div class="body_list_works" v-if="ticketList.length > 0">
            <div
              v-for="(item, index) in ticketList"
              :key="index"
              @click="selectTicket(item)"
            >
              <Works
                v-bind="$attrs"
                :workData="item"
                :ticketSelect="ticketSelect"
              ></Works>
            </div>
          </div>
          <div v-else>
            <div
              v-if="
                !!listParams.state ||
                listParams.state === 0 ||
                ticketList.length == 0
              "
            >
              暂无航线数据
            </div>
            <div v-else>请选择航线状态</div>
          </div>
        </div>
      </div>
    </div>

    <div class="pagination">
      <el-pagination
        v-if="ticketList.length > 0 && boxStatus == 1"
        @current-change="handleCurrentChange"
        :current-page.sync="listParams.page"
        :page-size="listParams.page_size"
        layout="total, prev, pager, next"
        :total="total"
        :pager-count="5"
        small
        background
        :hide-on-single-page="ifPagination"
      >
      </el-pagination>
    </div>

    <div v-if="showMask" class="full-mask" @click="showMask = false"></div>
  </div>
</template>

<script>
import moment from "moment";

import Works from "./works.vue";

import {
  getTicketListV3,
  ticketTicketStateV3,
  ticketDetailV3,
} from "@/api/view5";
export default {
  name: "TicketListBox",
  props: {
    dateValue: {
      type: Array,
      default: () => [],
    },
    boxStatus: {
      default() {
        return 1;
      },
    },
  },
  components: { Works },
  data() {
    return {
      ticketSelect: {}, // 选中任务
      // ! 发送值 任务列表传输发送值
      listParams: {
        begin_date: "2022-11-01", // 开始日期
        end_date: "2022-12-01", // 结束日期
        state: "", // 状态
        aim: "", // 类型
        page: 1,
        page_size: 10,
        line_name: "",
      },

      dateValue2: this.dateValue, // 时间

      ticketState: "", // 状态筛选
      ticketAim: "", // 状态筛选
      ticketStateOptions: [], // 状态选项
      ticketAimOptions: [], // 类型选项

      // 任务列表数据
      total: 100, // 总数
      ifPagination: true, // 显示分页器
      workTime: null, // 定时器

      ticketList: [
        // {
        //   address: "341", // 地址
        //   aim: "日常巡检", // 标题
        //   airline_name: "【环绕】1213", // 航线
        //   execute_time: "2022-12-13 15:55:03", // 执行时间
        //   mark_count: 6, // 标记数量
        //   photo_count: 50, // 照片数量
        //   state: "生产中", // 状态
        //   submit_time: "2022-12-13 15:49:31", // 提交时间
        //   thumbnail: null, // 图片路径
        // },
      ],

      showMask: false,
      isShowSearchName: false,

      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              console.log(picker);
              const end = new Date();
              const start = moment().add(-7, "day").toDate();
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = moment().add(-1, "month").toDate();
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = moment().add(-3, "month").toDate();
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近半年",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 180);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
    };
  },
  mounted() {
    this.initData();
    this.initBus();
  },
  methods: {
    initData() {
      this.listParams.begin_date = this.dateValue2[0];
      this.listParams.end_date = this.dateValue2[1];

      // ? 任务列表状态
      ticketTicketStateV3().then((res) => {
        if (res.error_code == 0) {
          this.ticketStateOptions = res.data.state;
          this.ticketAimOptions = res.data.type;
        }
      });

      this.getTicketList(1);
    },

    initBus() {
      let that = this;

      // 任务横向滚动监听
      const tabBar = that.$el.querySelector(".title");
      tabBar.addEventListener("mousewheel", that.handleScroll);

      window.addEventListener("click", (event) => {
        const e = event || window.event;
        if (
          that.$refs.searchInfo &&
          !that.$refs.searchInfo.contains(e.target)
        ) {
          that.isShowSearchName = false;
          that.clickTimes = 0;
        }
      });
    },
    // 横向滚动
    handleScroll(e) {
      // 0----down  1----up
      var direction = e.deltaY > 0 ? "0" : "1";
      const tabBar = this.$el.querySelector(".title");
      //下面的实现的是内部元素横向滚动，前提设置好内部元素横向的滚动样式了
      if (direction === "0") {
        tabBar.scrollLeft += 30;
      } else {
        tabBar.scrollLeft -= 30;
      }
    },

    // ! 获取任务列表
    getTicketList(num) {
      console.log("vueX", this.$store.getters);
      this.hideSearchHistory();
      var _this = this;
      if (num == 1) {
        this.saveHistory();
        this.listParams.page = 1;
      }
      let tickets = document.querySelector(".body_list_works");
      _this.listLoading = true;

      getTicketListV3({
        ...this.listParams,
      })
        .then((res) => {
          if (res.error_code == 0 && res.data) {
            this.total = res.data.total;
            this.ticketList = res.data.items;
            this.ticketList.map((work) => {
              if (work.is_del === 1) {
                work.state = "删除";
              }

              tickets.scrollTop = 0;
            });
          } else {
            console.log("无数据");
            this.ticketList = [];
            this.total = 0;
            return;
          }
        })
        .catch((err) => {})
        .finally(() => {
          _this.listLoading = false;
        });
    },
    // * 日期筛选
    changeData(val) {
      this.listParams.begin_date = val[0];
      this.listParams.end_date = val[1];
      this.getTicketList(1);
    },
    // * 状态筛选
    ticketOptionChange(val) {
      this.listParams.page = 1;
      this.getTicketList(1);
    },
    // * 分页器
    handleCurrentChange() {
      this.getTicketList();
    },

    // ! 选中任务
    selectTicket(val) {
      this.ticketSelect = val;
      ticketDetailV3({ ticket_id: val.ticket_id }).then((res) => {
        if (res.error_code == 0) {
          this.$parent.ticketInfoData = res.data;
          this.$emit("boxStatusChange", 3);
        } else {
          this.$message.warning(res.msg);
        }
      });
    },

    // ! 未知 历史？？？
    historySearch(queryString, cb) {
      const res = sessionStorage.getItem("view5SearchHistory");
      if (res) {
        cb(JSON.parse(res));
      } else {
        cb([]);
      }
    },
    handleSelectHistory(item) {
      console.log("0822000", item);
      this.listParams.line_name = item;
      this.getTicketList(1);
    },
    saveHistory() {
      if (this.listParams.line_name.trim()) {
        let res = sessionStorage.getItem("view5SearchHistory");
        if (!res) {
          res = [];
        } else {
          res = JSON.parse(res);
        }
        if (res.includes(this.listParams.line_name.trim())) {
          const newArray = [];
          res.forEach(
            (item) =>
              item !== this.listParams.line_name.trim() && newArray.push(item)
          );
          res = newArray;
        }
        res.unshift(this.listParams.line_name.trim());
        if (res.length > 5) {
          res = res.slice(0, 5);
        }
        sessionStorage.setItem("view5SearchHistory", JSON.stringify(res));
      }
    },
    hideSearchHistory() {
      const elements = document.getElementsByClassName("el-autocomplete");
      if (elements.length > 0) {
        elements[0].__vue__.activated = false;
      }
    },
    // ! 未知 筛选？？？
    searchNameShow() {
      var _this = this;

      if (_this.isShowSearchName == false) {
        _this.isShowSearchName = true;
        setTimeout(() => {
          this.$refs.inputRef.focus();
        }, 5);
      }
      if (_this.isShowSearchName == true) {
        _this.clickTimes++;
        console.log(_this.clickTimes);
        if (_this.clickTimes !== 1) {
          if (_this.listParams.line_name == "") {
            _this.$message({
              message: "请输入搜索内容",
              type: "warning",
            });
            return false;
          }
          _this.getTicketList(1);
        }
      }
    },
    searchNameList(e) {
      var _this = this;
      if (e.keyCode == 13) {
        _this.getTicketList(1);
      }
    },
    queryKeyNull() {
      var _this = this;
      _this.getTicketList(1);
    },
  },
  computed: {},
  watch: {
    dateValue2(newVal, oldVal) {
      if (newVal[0] !== oldVal[0] || newVal[1] !== oldVal[1]) {
        // console.log("changeDateValue emit");
        this.$bus.emit("changeDateValue", newVal);
      }
      // this.$emit('changeDateValue', newVal)
    },
  },
};
</script>

<style lang="scss" scoped>
$color1: #18abf3;

.ticketListBox {
  .list {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;

    .title {
      display: flex;
      margin: 10px;
      border: 0.1px solid #cccccc50;
      height: 30px;
      line-height: 30px;
      background: #ffffff20;
      border-radius: 5px;
      position: relative;

      .searchInfo {
        display: flex;
        flex-direction: row-reverse;
        position: absolute;
        top: -1px;
        right: -1px;
        z-index: 100000;
        background: #304147;
        width: auto;

        .searchBtn {
          color: #ffffff;
          background: #14375d;
          border: 1px solid #697479;
          // border-right: none;
          display: inline-block;
          width: 50px;
          height: 30px;
          line-height: 30px;
          text-align: center;
          cursor: pointer;
          border-radius: 0px 4px 4px 0;

          i {
            font-size: 14px;
            color: #b0c0c8;
          }
        }
      }

      .searchInfo::v-deep {
        .el-input {
          width: 238px;

          .el-input__inner {
            background: #304047;
            height: 30px;
            border: 1px solid #697479;
            border-right: none;
            border-radius: inherit;
            color: #ffffff;
            border-radius: 4px 0px 0px 4px;
          }

          .el-input__suffix {
            .el-input__suffix-inner {
              .el-input__clear {
                line-height: 30px;
              }
            }
          }
        }
      }

      .title_left ::v-deep {
        flex: 3;
        height: 100%;
        padding-right: 45px;

        .mydatepicker {
          width: 100%;
          height: 100%;
        }

        .el-input__inner {
          background-color: transparent;
          padding: 5px;
          border: none;
        }

        .el-range-input,
        .el-range-separator {
          background-color: transparent;
          color: #fff;
          padding: 0;

          &::placeholder {
            color: #fff;
          }
        }
      }

      .title_right {
        flex: 1;
        font-size: 12px;

        .distance_svg_icon {
          font-size: 15px;
        }
      }
    }

    .body {
      flex: 1;
      width: 100%;
      height: 100%;

      .body_title {
        background-image: url("~@/assets/box_title_back1.png");
        background-size: 100% 100%;
        text-align: left;
        width: 100%;
        height: vh(30);
        margin: vh(5) auto;
        line-height: vh(30);
        font-size: 14px;
        color: white;
        padding: 0px 10px;

        display: flex;
        justify-content: space-between;

        .body_title_select {
          ::v-deep .el-input__inner {
            background-color: rgba(183, 178, 178, 0.2);
            color: #fff;
            width: 100px;
            height: 24px;
            line-height: 24px;
            font-size: 12px;
            padding-right: 15px;

            &::placeholder {
              color: #fff;
            }
          }
          .workTypeSelect {
            margin-right: 5px;
          }
          .workStateSelect {
          }
        }
      }

      .body_list {
        height: calc(90vh - 135px);
        // transition: height 0.3s;
        // border: 1px solid $color1;
        margin-top: 5px;

        .body_list_works {
          height: 100%;
          overflow: auto;
        }
      }
    }
  }

  .pagination {
    padding-right: 5px;
    width: 100%;
    position: absolute;
    bottom: 5px;
    right: 5px;
    text-align: right;

    ::v-deep .el-pagination {
      .el-pagination__total {
        color: #fff;
      }

      .btn-prev,
      .btn-next,
      .btn-quickprev,
      .btn-quicknext {
        background-color: transparent;
        color: #fff;
        margin: 0;
      }

      .el-pager {
        .number {
          background-color: transparent;
          color: #fff;
          margin: 0;
        }

        .active {
          color: $color1;
        }
      }

      button:disabled {
        color: #606266;
      }

      button {
        color: #fff;
      }
    }
  }
}
.historyItem {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: flex-start;
  background-color: rgba(0, 0, 0, 0);
  color: white;
  padding: 8px;

  .history-icon {
    width: 15px;
    height: 15px;
    margin-right: 8px;
  }

  .history-text {
    font-size: 13px;
    line-height: 15px;
    align-content: center;
    overflow: hidden; /* 超出一行文字自动隐藏 */
    text-overflow: ellipsis; /*文字隐藏后添加省略号*/
    white-space: nowrap; /*强制不换行*/
  }
}
</style>
